from urllib import request, parse
import ssl
import json

# https required
context = ssl._create_unverified_context()

# with request.urlopen(
#     'https://m.ctrip.com',
#     context=context
# ) as f:
#     data = f.read()
#     print('Status:', f.status, f.reason)
#     for k, v in f.getheaders():
#         print('%s: %s' % (k, v))
#     print('Data:', data.decode('utf-8'))

# 模拟post请求

# 城市模糊搜索
target_url = 'http://127.0.0.1:3000/rest'

# head = json.dumps('{"cid": 234234234}')

# print(type(head))

# post_data = parse.urlencode([
#     ('key', 'aa'),
#     ('maxcount', 20),
#     ('pttype', 17),
#     ('ptgroup', 17),
#     ('head',('cid', 2324))
# ])

# print(post_data)
json_data = {
    'head': {
        'cid': 23423
    }
}
post_data = json.dumps(json_data)
# print(post_data)

# print(type(post_data))
# print(post_data.encode('utf-8'))

req = request.Request(target_url)

# 缺少请求头json
req.add_header('Content-Type', 'application/json')

with request.urlopen(req, data=post_data.encode('utf-8'), context=context) as content:
    print(content.read().decode())